package com.gexin.controller.commom;
import com.gexin.common.AppGlobal;
import com.gexin.common.cache.CacheUtils;
import com.gexin.common.model.AjaxCmd;
import com.gexin.common.utils.IdGenerateUtils;
import com.gexin.common.utils.QiNiuUtil;
import com.gexin.common.utils.StringUtil;
import com.gexin.core.web.BaseController;
import com.gexin.weixin.kit.WxConfigKit;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
/**
 * 七牛的token 的接口
 * @author 肖德明
 *
 */
@ControllerBind(controllerKey = "/api/qiniu")
public class QiniuController extends BaseController {
	public void index() {
		String token  = CacheUtils.get(AppGlobal.Qiniu_Bucket);
		//String token  = null;
		if(token==null){
			StringMap  map =new StringMap();
			map.put("returnBody", "{\"key\": $(key), \"hash\": $(etag), \"width\": $(imageInfo.width), \"height\": $(imageInfo.height) ,\"mimeType\":${mimeType}}");
			Auth auth = Auth.create(AppGlobal.Qiniu_AK,AppGlobal.Qiniu_SK);
			token = 	auth.uploadToken(AppGlobal.Qiniu_Bucket,null,3600,map);
			CacheUtils.set(AppGlobal.Qiniu_Bucket, token, 2000);
		}
		renderJson("uptoken", token); 
	}
	
	/**
	 * 抓取远程的图片
	 */
	public void fetch(){
		String serverid = getPara("serverid");
		String key = getPara("key");
		if(StringUtil.isBlank(serverid)==false){
			ApiConfigKit.setThreadLocalAppId(WxConfigKit.getApiConfig(getParaToInt("appid",1)).getAppId());
			String token = AccessTokenApi.getAccessToken().getAccessToken();
			String url = QiNiuUtil.fetch(QiNiuUtil.getWxRes(token, serverid),key+"/"+StringUtil.generID());
			System.err.println(url);
			if(url!=null){
				renderJson(new AjaxCmd(url));
				
			}else{
				renderJson( new AjaxCmd(false));
			}
		}else{
			renderJson(new  AjaxCmd(false, "参数错误"));
		}
	}
	
	//远程抓取图片
	public void t(){
		System.err.println(QiNiuUtil.upload("D:\\new.gif",IdGenerateUtils.getId()+".jpg"));;
		renderText(QiNiuUtil.fetch("http://7xolfu.com1.z0.glb.clouddn.com/@/images/20151205/1449294893897022562.png","res/"+StringUtil.generID()));
	}
	
	
}


